package com.gioo.android;



import java.util.HashMap;
import java.util.Map;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.os.SystemClock;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.appang.point.AppangPointModule;
import com.google.android.gcm.GCMRegistrar;
import com.localytics.android.*;

public class MovieonsActivity extends Activity {
	final Activity activity = this;
	public static Activity movieonsActivity = null;
	ProgressDialog mProgress;
	
	private static final String REON_SERVICE = "REON_SERVICE";
	
	ImageView imageView1;
	WebView infoWebView;
	//ProgressBar loadingIndicator;
	
	private final static String LOCALYTICS_APP_KEY ="993aa4824b9ccb7161fa671-96c745ea-d603-11e1-4832-00ef75f32667";
	ProgressBar mProgressHorizontal;
	
	private LocalyticsSession localyticsSession;
	
	AppangPointModule apm = null;
	
	Intent registrationIntent = new Intent();
	
	String c2dm_msg;
	
	static final String SENDER_ID = "59375700515";
	
	static String phoneNumber;
	static String deviceId;
	static Account[] googleAccount;
	static String googleAccounts = "";
	
	public static Activity mainActivity = null;
	public Context mainContext = null;
	
	static public String registrationId;
	
	
	Intent intentMyService;        
    BroadcastReceiver receiver;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {

		// 스플래시 화면 띄우기
        startActivity(new Intent(this, SplashActivity.class));
        
        mainActivity = this;
        mainContext = this;
        
		super.onCreate(savedInstanceState);
	    setContentView(R.layout.webview);
	    
	    
	    this.localyticsSession = new LocalyticsSession( this.getApplicationContext(), LOCALYTICS_APP_KEY);
	    this.localyticsSession.open();
	    this.localyticsSession.upload();
	    
	    apm = new AppangPointModule();
		apm.execute(this, "527436a634b01c490844f5163d973634");
		
		
		/*
		 * get device informations
		 * */
		TelephonyManager telManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);	
		AccountManager accManager = (AccountManager)getSystemService(ACCOUNT_SERVICE);
		phoneNumber = telManager.getLine1Number();
		deviceId = telManager.getDeviceId();
		googleAccount = accManager.getAccounts();
		
		for(int i=0; i<googleAccount.length; i++){
			if(googleAccount[i] != null){
				googleAccounts += (googleAccount[i].name +  "|" + googleAccount[i].type + ", ");
			}
		}
		Log.d("dv-info", googleAccounts);
		
		
		/** 
		 *  Register GCM
		 * */
		GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);
		final String regId = GCMRegistrar.getRegistrationId(this);
		GCMRegistrar.register(this, SENDER_ID);
		/*
		if(regId.equals("")){
			GCMRegistrar.register(this, SENDER_ID);
		}else{
			Log.d("GCM", "Already registered : " + regId );
		}
		*/
		
		//등록하기
		Intent registrationIntent = new Intent("com.google.android.c2dm.intent.REGISTRATION");
		// sets the app name in the intent
		registrationIntent.putExtra("app", PendingIntent.getBroadcast(this, 0, new Intent(), 0));
		registrationIntent.putExtra("sender", SENDER_ID);
		
		
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
                | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
		
		// for syncronizing cookie
		CookieSyncManager.createInstance(this);
	    
		
		//regist zombie service
				intentMyService = new Intent(this,PersistentService.class);        // 죽지않는 좀비 서비스
		        receiver = new RestartService();                                                    // 리시버 등록
		        try{
		        	IntentFilter mainFilter = new IntentFilter("com.gioo.android.serviceaction");      // xml에서 정의해도 됨
		        	registerReceiver(receiver, mainFilter);                                               // 리시버 저장
		        	startService(intentMyService);                                                           // 서비스 시작 
		        }
		        	catch (Exception e) {
		        		Log.d("REON_SERVICE",e.getMessage()+"");
		        	}	
		        
		
		
	    initialize();
	}
	
	
	@Override
	protected void onDestroy() {
		
		if (null != apm) {
			apm.Destroy();
			apm = null;
		}
		
		Log.i("REON_SERVICE", "onDestroy");
		unregisterReceiver(receiver);                                                               //리시버 삭제(?) 안하면 에러!!
		
		
		
		super.onDestroy();
	}
	
	public void onResume()
	{
	    super.onResume();
	    this.localyticsSession.open();
	    
	    // for syncronizing cookie
	    CookieSyncManager.getInstance().startSync();
	}
	public void onPause()
	{
	    this.localyticsSession.close();
	    this.localyticsSession.upload();
	    
	    // for syncronizing cookie
	    CookieSyncManager.getInstance().stopSync();
	    
	    super.onPause();
	}
	
	
	@Override
	public void onBackPressed() {
		//super.onBackPressed();
		if(infoWebView.canGoBack()){
			infoWebView.goBack();
		}else{
			new AlertDialog.Builder(this)
			  .setIcon(R.drawable.icon)
			  .setTitle(R.string.app_name)
			  .setMessage("종료하시겠습니까?")
			  .setPositiveButton("종료", new OnClickListener() {
			   @Override
			   public void onClick(DialogInterface dialog, int which) {
				   MovieonsActivity.this.finish();
			   }
			  })
			  .setNegativeButton("취소", null)
			  .show();
			  
		}
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu){
		
		
		
		menu.add(0,1,0,"무비온즈 홈").setIcon(R.drawable.home);
		menu.add(0,2,0,"내정보").setIcon(R.drawable.profile);
		menu.add(0,3,0,"종료").setIcon(R.drawable.exitapp);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem Item){
		
		switch(Item.getItemId()){
		case 1:
			infoWebView.loadUrl("http://movie.twitaddons.com");
			return true;
		case 2:
			infoWebView.loadUrl("http://movie.twitaddons.com/timeline/");
			return true;
		case 3:
			new AlertDialog.Builder(this)
			  .setIcon(R.drawable.icon)
			  .setTitle(R.string.app_name)
			  .setMessage("종료하시겠습니까?")
			  .setPositiveButton("종료", new OnClickListener() {
			   @Override
			   public void onClick(DialogInterface dialog, int which) {
				  
					
				   MovieonsActivity.this.finish();
			   }
			  })
			  .setNegativeButton("취소", null)
			  .show();
			return true;
		}
		
		
		
		
		return super.onOptionsItemSelected(Item);
	}
	
	/**
     * 스플래시 표시하는 것과 초기화를 동시에 진행시키기 위하여 쓰레드 처리
     *
     */
    private void initialize()
    {
        InitializationRunnable init = new InitializationRunnable();
        new Thread(init).start();
    }


    /**
     * 초기화 작업 처리
     *
     */
    class InitializationRunnable implements Runnable
    {
        public void run()
        {
        	Log.d(null, "chk");
            // 여기서부터 초기화 작업 처리
        	
        	//init apppang module
        	
        	
        	
            // do_something
        	
        	infoWebView = (WebView)findViewById(R.id.webView01);
    	    imageView1 = (ImageView)findViewById(R.id.imageView1);
    	    // loadingIndicator = (ProgressBar)findViewById(R.id.loadingIndicator);
    	    
    	    
    	    mProgressHorizontal = (ProgressBar) findViewById(R.id.progress_horizontal);
    	    // 자바 스크립스 사용
    	    infoWebView.getSettings().setJavaScriptEnabled(true);
    	    infoWebView.getSettings().setBuiltInZoomControls(true);
    	    infoWebView.getSettings().setSupportZoom(true);
    	    infoWebView.getSettings().setUseWideViewPort(true);
    	    infoWebView.setInitialScale(1);
    	    infoWebView.getSettings().setPluginsEnabled(true);
    	    infoWebView.getSettings().setPluginState(PluginState.ON_DEMAND);
    	    infoWebView.getSettings().setSupportMultipleWindows(true);
    	    infoWebView.getSettings().setAllowFileAccess(true);
    	    infoWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
    	    
    	    
    	    
    	   
    	    TelephonyManager systemService = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
    	    
    	    WebSettings webSettings = infoWebView.getSettings();
    	    StringBuffer userAgent = new StringBuffer(webSettings.getUserAgentString());
    	    userAgent.append("; "+"dvid"+systemService.getLine1Number()+";");
    	    
    	    webSettings.setUserAgentString(userAgent.toString());
    	    
    	    Log.d(null, userAgent.toString());
    	    
    	    
    	    infoWebView.loadUrl("http://movie.twitaddons.com");
    	 // 내꺼 webview 사용 명시
    	    infoWebView.setWebViewClient(new InfoWebViewClient());
    	    
    	    infoWebView.setVerticalScrollbarOverlay(true);
    	    
    	    infoWebView.setWebChromeClient(new WebChromeClient(){
    	    	@Override
    	    	public void onProgressChanged(WebView view, int newProgress){
    	    		mProgressHorizontal.setProgress(newProgress);
    	    	}
    	    	
    	    	
    	    });
    	    
    	    
    	    
    	    startService(registrationIntent);
    	    
    	    
    		
        }
        
        
    }
    


    
   
    public class InfoWebViewClient extends WebViewClient {

    	
    	
    	
    	/**
		 * url 주소에 해당하는 웹페이지를 로딩
		 */
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			
				CookieManager cookieManager = CookieManager.getInstance();
				
				
				Log.d("cookie", cookieManager.getCookie("http://movie.twitaddons.com"));
			
			
			if(url.startsWith("kakao")){
				localyticsSession.tagEvent("ATTEMPTING_KAKAO");
				localyticsSession.upload();
			}
			
			if(url.startsWith("http://movie.twitaddons.com/account/login.php")){
				localyticsSession.tagEvent("ACCESSING_LOGIN_PAGE");
				localyticsSession.upload();
				
				
				
				//CookieManager cookieManager = CookieManager.getInstance();
				
				

				// CookieManager에 특정 Domain의 Cookie 추가
				cookieManager.setCookie("http://movie.twitaddons.com", "gcmtoken="+registrationId);  // "cookieKey=value" 

				// Cookie 추가 후에 Sync 수행
				CookieSyncManager.getInstance().sync();
				
				
				//infoWebView.loadUrl("javascript:alert('"+"registratedId"+"')");
				
			}
			
			try{
				
				
				 Map <String,String> values = new HashMap<String,String> ();
					values.put("TARGET_PAGE", url);
					localyticsSession.tagEvent("MOVING_PAGE", values);
					localyticsSession.upload();
					
					if(url.indexOf("&") != -1){
						//Log.d("noparam", String.valueOf(url.indexOf("?")));
						Log.d("noparam", url.substring(0,url.indexOf("?")));
					}else{
						Log.d("noparam", url);
					}
				
				localyticsSession.tagEvent("MOVING_PAGE");
				localyticsSession.upload();
			}catch(Error e){
				
			}
			
			if(url.startsWith("http://movie") ||
					url.startsWith("http://movie") ||
					url.startsWith("movie") ||
					url.startsWith("movie") ||
					url.startsWith("https://logins.daum") ||
					url.startsWith("https://apis") ||
					url.startsWith("https://twitter.com/oauth/") ||
					url.startsWith("http://me2day.net/p/me2/login") ||
					url.startsWith("http://me2day.net/api") ||
					url.startsWith("https://me2day.net/openid") ||
					url.startsWith("http://nid.naver.com") ||
					url.startsWith("https://www.facebook.com/login") ||
					url.startsWith("https://www.facebook.com/dialog") ||
					url.startsWith("https://m.facebook.com/dialog") || 
					url.startsWith("http://m.facebook.com/login.php") || 
					url.startsWith("http://login.daum.net/accounts") || 
					url.startsWith("movie")
					)
			{
				view.loadUrl(url);
			}else{
				Log.d("external links", url);
				infoWebView.stopLoading();
				infoWebView.goBack();
				Intent i = new Intent();
				i.setAction(Intent.ACTION_VIEW);
				i.setData(Uri.parse(url));
				startActivity(i);
			}
			
			/*
			 if(url.startsWith("kakaolink:") || 
					 url.startsWith("http://www.you") ||
					 url.startsWith("http://m.you")
					 )
			 {
				infoWebView.stopLoading();
				infoWebView.goBack();
                Intent i = new Intent();
                i.setAction(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                startActivity(i);
            }else{
            	view.loadUrl(url);
            }
            */
			
			
            // 안드로이드 자체 WebView가 아닌 내가 만든 WebView 직접 사용한다고 명시
			return true;
		}
		
		
		
		/**
		 * 웹페이지 로딩이 시작할 때 처리
		 */
		@Override
		public void onPageStarted(WebView view, String url, Bitmap favicon) {
			/*
			 * if (mProgress == null) { mProgress = new
			 * ProgressDialog(activity);
			 * mProgress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			 * mProgress.setTitle("무비온즈 로딩중");
			 * mProgress.setMessage("잠시만 기다려주세요!");
			 * mProgress.setCancelable(false); mProgress.setButton("취소", new
			 * DialogInterface.OnClickListener() {
			 * 
			 * @Override public void onClick(DialogInterface dialog, int
			 * whichButton) { mProgress.dismiss(); } }); //mProgress.show();
			 * //imageView1.setVisibility(View.VISIBLE);
			 * 
			 * 
			 * 
			 * 
			 * }
			 */
			
			
			super.onPageStarted(view, url, favicon);
			mProgressHorizontal.setVisibility(View.VISIBLE);
			//loadingIndicator.setVisibility(View.VISIBLE);
		}
		  
		/**
		 * 웹페이지 로딩중 에러가 발생했을때 처리
		 */
		@Override
		public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
			Toast.makeText(activity, "Loading Error" + description, Toast.LENGTH_SHORT).show();
			
			

		   
			/*
			if (imageView1.getVisibility() == View.VISIBLE) {
				//mProgress.dismiss();
				//imageView1.setVisibility(View.INVISIBLE);
			}
			*/
		}
		  
		/**
		 * 웹페이지 로딩이 끝났을 때 처리
		 */
		@Override
		public void onPageFinished(WebView view, String url) {
			/*
			if (imageView1.getVisibility() == View.VISIBLE) {
			//mProgress.dismiss();
				//imageView1.setVisibility(View.INVISIBLE);
			}
			*/
			//loadingIndicator.setVisibility(View.INVISIBLE);
			
			
			super.onPageFinished(view, url);
			mProgressHorizontal.setVisibility(View.INVISIBLE);
			
			
			
		}
    }
    
    
    
    
    
}
	 